/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package CameraView;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.media.control.VideoControl;
import javax.microedition.amms.control.camera.*;
import javax.microedition.io.file.*;
import java.io.*;
import javax.microedition.io.*;
import java.lang.Math.*;
import sUtils.*;

public class CameraView extends MIDlet implements CommandListener {

    private Display display;
    private Command exit,capture,back;
    VideoCanvas canvas;

    public CameraView() {
        Lang.init();
        exit = new Command(Lang.word("Quit","Beenden"), Command.EXIT, 0);
        capture = new Command(Lang.word("Snapshot","Foto"), Command.OK, 1);
        back = new Command(Lang.word("Back","Zurück"), Command.BACK, 2);
        canvas = null;
    }

    public void startApp() {
        display = Display.getDisplay(this);
        canvas = new VideoCanvas();
        canvas.addCommand(capture);
        canvas.addCommand(exit);
        canvas.setCommandListener(this);
        display.setCurrent(canvas);

    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void commandAction(Command c, Displayable s) {
        if (c == exit) {
            canvas.done();
            destroyApp(true);
            notifyDestroyed();
        } else
        if (c == capture) {
            canvas.removeCommand(capture);
            canvas.addCommand(back);
            canvas.takePhoto();

        }
        if (c == back) {
            canvas.removeCommand(back);
            canvas.addCommand(capture);
            canvas.live();
        }
    }

 class VideoCanvas extends Canvas  {
    int color=0, size=1;
    Timer timer;
    VideoControl videoControl=null;
    FlashControl flashControl=null;
    Image bg=null;
    int timeout=0;
    int [] rgb=null;
    int w, h, px, py, colr=0, colb=0, colg=0;
    Player player=null;

    public VideoCanvas()  {
        bg = null;
        init();
        timer = new Timer();
        timer.schedule(new updateTask(this), 100, 100);
    }

    void init()
    {
        int width = getWidth();
        int height = getHeight();
        try {
            player = Manager.createPlayer("capture://video");
            player.realize();
            flashControl = (FlashControl)player.getControl("FlashControl");
            videoControl = (VideoControl)player.getControl("VideoControl");
            videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
            try {
                videoControl.setDisplayLocation(0, 40);
                videoControl.setDisplaySize(width, height - 40);
            } catch (MediaException me) {}
            videoControl.setVisible(true);
            player.start();
        } catch (IOException ioe) {} catch (MediaException me) {
        }
    }

    void done()
    {
        if (player!=null) {
            player.deallocate();
            player.close();
            player=null;
            videoControl=null;
            flashControl=null;
        }
    }

    String intToStr( int i, int len )
    {
        StringBuffer sb = new StringBuffer(10);
        int n = 1;
        for ( int j=1; j<len; j++ ) n*=10;
        if (i<0) { sb.append("-"); i=-i; }
        for ( int j=0; j<len; j++ )
        {
            sb.append((char)('0'+(i/n)%10));
            n/=10;
        }
        return sb.toString();
    }

    class updateTask extends TimerTask {
        private Canvas canvas;
        updateTask( Canvas c ){  canvas = c;  }
        public void run() {  canvas.repaint(); }
    }

    public void paint(Graphics g) {
        synchronized(this)
        {
            int width = getWidth();
            int height = getHeight();

            g.setColor(0x0);
            g.fillRect(0,0,width,40);
            if (bg!=null)
            {
                g.drawImage(bg, 0, 40, 0);
                g.setColor(0xffffff);g.drawArc(px-size,py-size,size+4,size+4,0,360);
                g.setColor(0);g.drawArc(px-size-1,py-size-1,size+6,size+6,0,360);

                g.setColor(0x40407f);
                g.setFont( Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN,Font.SIZE_SMALL));
                StringBuffer s = new StringBuffer(50);
                s.append("R="); if (colr<100) s.append(" "); if (colr<10) s.append(" "); s.append(colr);
                s.append(" G="); if (colg<100) s.append(" "); if (colg<10) s.append(" "); s.append(colg);
                s.append(" B="); if (colb<100) s.append(" "); if (colb<10) s.append(" "); s.append(colb);
                s.append(" Ø="); s.append(size*2+1);
                g.drawString( s.toString(),4,4,0);
            }
        }
    }

    public void setPos( int x, int y )
    {
        if (bg!=null && rgb!=null)
        {
            px = x; py = y; y-=40;
            int w = bg.getWidth();
            int h = bg.getHeight();

            colr=0; colb=0; colg=0;
            int c=0, col;
            for ( int iy=-size, dy=y-size; iy<=size; iy++,dy++)
            if ( dy>=0 && dy<h )
            for ( int ix=-size, dx=x-size; ix<=size; ix++,dx++)
            if ( dx>=0 && dx<w)
            {
                col = rgb[dx+dy*w];
                colr += (col>>16)&0xff;
                colg += (col>>8)&0xff;
                colb += col&0xff;
                c++;
            }

            colr /= c;
            colg /= c;
            colb /= c;
            repaint();
        }
    }
    public void pointerPressed( int x, int y )
    {
        size=0;
        setPos(x,y);
    }
    public void pointerDragged( int x, int y )
    {
        int dx = px-x; int dy = py-y;
        size = (int)( Math.sqrt( dx*dx + dy*dy ) )/3;
        setPos(px,py);
    }
    public void pointerReleased( int x, int y )
    {
    }

    public void live()
    {
        synchronized(this)
        {
            bg = null;
            timeout = -1;
            init();
        }
    }
    public void takePhoto()
    {
        synchronized(this)
        {
            StringBuffer sb = new StringBuffer(50);
            Calendar dt = Calendar.getInstance();

            sb.append(intToStr(dt.get(Calendar.YEAR),4));
            sb.append(intToStr(dt.get(Calendar.MONTH)+1,2));
            sb.append(intToStr(dt.get(Calendar.DAY_OF_MONTH),2));
            sb.append("_");
            sb.append(intToStr(dt.get(Calendar.HOUR_OF_DAY),2));
            sb.append(intToStr(dt.get(Calendar.MINUTE),2));
            sb.append(intToStr(dt.get(Calendar.SECOND),2));
            
            try {
                flashControl.setMode(FlashControl.AUTO);
                byte[] raw = videoControl.getSnapshot(null);
                bg = Image.createImage(raw, 0, raw.length);
                w = bg.getWidth();
                h = bg.getHeight();
                rgb = new int[w*h];
                bg.getRGB(rgb,0,w,0,0,w,h);
                setPos(w/2,h/2);

                FileConnection f = (FileConnection) Connector.open ("file:///Photo/" +
                        Lang.word("Photo_","Foto_")+sb.toString()+".jpg");
                if (f.exists()) f.delete();
                f.create();
                f.openOutputStream().write(raw, 0, raw.length);
            }  catch(MediaException e) {} catch(IOException e) {}
            timeout=50;
            done();
        
        }
    }
    }
}